package com.activenetwork.util.grid.condition;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConditionBuilder {
	
	private List<Condition> conditionList;
	private static Logger logger = LoggerFactory.getLogger(ConditionBuilder.class);
	/**
	 * Add condition to check td is null
	 * @param condition
	 * @param column
	 */
	public void add(EqualCondition condition, int column){
		condition.setColumn(column);
		condition.setValue(null);
		conditionList.add(condition);
	}
	/**
	 * Add various condition
	 * @param condition
	 * @param column
	 * @param args
	 */
	public void add(Condition condition, int column, String...args){
		if(conditionList == null) 
			conditionList = new ArrayList<Condition>();
		
		if(column < 0){
			throw new RuntimeException("Builder error - column smaller than 0.");
		}
		if(StringUtils.isBlank(args[0])){
			logger.warn("Expect value can not be null for column " + column);
			return;
		}
		
		if(condition instanceof EqualCondition){
			((EqualCondition) condition).setColumn(column);
			((EqualCondition) condition).setValue(args[0]);
		}else if(condition instanceof RegexCondition){
			((RegexCondition) condition).setColumn(column);
			((RegexCondition) condition).setPattern(Pattern.compile(args[0]));
		}else if(condition instanceof ContainCondition){
			((ContainCondition) condition).setColumn(column);
			((ContainCondition) condition).setCollection(Arrays.asList(args));
		}else if(condition instanceof EnabledCondition){
			((EnabledCondition) condition).setColumn(column);
		}else if(condition instanceof EqualValueCondition){
			((EqualValueCondition) condition).setColumn(column);
			((EqualValueCondition) condition).setValue(args[0]);
		}else if(condition instanceof HasContentCondition){
			((HasContentCondition) condition).setColumn(column);
			((HasContentCondition) condition).setHasContent(Boolean.parseBoolean(args[0]));
		}else if(condition instanceof NotEqualCondition){
			((NotEqualCondition) condition).setColumn(column);
			((NotEqualCondition) condition).setValue(args[0]);
		}else if(condition instanceof ContainsCondition){
			((ContainsCondition) condition).setColumn(column);
			((ContainsCondition) condition).setValue(args[0]);
		}else if(condition instanceof RecordCheckboxAttributeCondition){
			((RecordCheckboxAttributeCondition)condition).setColumn(column);
			((RecordCheckboxAttributeCondition)condition).setAttr(args[0]);
			((RecordCheckboxAttributeCondition)condition).setValue(args[1]);
		}
		
		conditionList.add(condition);
		
	}
	
	public Condition[] build(){
		if(conditionList == null){
			conditionList = new ArrayList<Condition>();
		}
		Condition[] conditions = conditionList.toArray(new Condition[conditionList.size()]);
		return conditions;
	}
	
}
